package com.oazon.moco.playlist.db;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.moco.launcher.R;

public class MocoDB extends SQLiteOpenHelper {

	private static final String TAG = "PlayListDB";
 
	private Context context;
	private static final String DATABASE_NAME = "moco.sqlite";
	private static final int DATABASE_VERSION = 7;

	public MocoDB(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(TAG, "onCreateDB");
		String creatTable = getSqlFormStrame(context.getResources()
				.openRawResource(R.raw.moco));
		String[] strTables = creatTable.split("[;]");

		for (int i = 0; i < strTables.length; i++) {
			Log.i(TAG, strTables[i] + ";\r\n");
			try{
				db.execSQL(strTables[i] + ";\r\n");
			}catch(Exception e){
				Log.e(TAG, "sql run error: "+e.getMessage());
			}
		}
		Log.i(TAG, "onCreateSuccess");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (newVersion == oldVersion) {
			return;
		}
		Log.i(TAG, "onUpgrade");
		onCreate(db);
		Log.i(TAG, "onUpgrade success");

	}

	private String getSqlFormStrame(InputStream inputStream) {
		String temp = "";

		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = "";
			StringBuffer stringBuffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				stringBuffer.append(str);
			}
			temp = stringBuffer.toString();
			Log.i(TAG, temp);
			bufferedReader.close();
			inputStreamReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	}
}
